package com.test.javafaq_faq.controller;


import com.test.javafaq_commons.entity.Answer;
import com.test.javafaq_commons.vo.R;
import com.test.javafaq_faq.service.IAnswerService;
import com.test.javafaq_faq.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {

    @Autowired
    IAnswerService answerService;

    @GetMapping("/{answerId}/solved")
    public R solved(@PathVariable Integer answerId){
        //log.debug("开始采纳答案:{}",answerId);
        boolean isSolved = answerService.accept(answerId);
        if(isSolved)
            return R.accepted("采纳完成!");
        else
            return R.notFound("已经采纳过或找不到答案");
    }


    @PostMapping
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public R postAnswer(@Validated AnswerVo answerVo, BindingResult res, @AuthenticationPrincipal UserDetails user){
        if(res.hasErrors()){
            String msg = res.getFieldError().getDefaultMessage();
            log.debug(msg);
            return R.unproecsableEntity(msg);
        }
        log.debug("开始新增回答:{}",answerVo);
        Answer answer = answerService.saveAnswer(answerVo,user.getUsername());
        return R.create(answer);
    }

    //  localhost:8080/v1/answers/question/150
    @GetMapping("/question/{id}")
    public R<List<Answer>> questionAnswers(@PathVariable Integer id){
        if(id == null)
            return R.notFound("ID不存在!");
        List<Answer> answers = answerService.getAnswersByQuestionId(id);
        return R.ok(answers);
    }



}
